from calendar import c
from dataclasses import dataclass, field
from typing import Dict, Optional
import os

# node_type解读：
# d = 目录
# f = 文件  
# l = 符号链接
# b = 块设备
# c = 字符设备
# p = FIFO
# s = 套接字
# u = 未知

# ----- 树节点的数据结构 -----
@dataclass
class FileTreeNode:
    name: str
    node_type: str          # "d" (目录) 或 "f" (文件)
    children: Dict[str, 'FileTreeNode'] = field(default_factory=dict)
    parent: Optional['FileTreeNode'] = None
    abs_path: str = ""

    def __post_init__(self):
        if self.node_type == "d":
            # 自动在结尾加一个/
            self.abs_path = self.abs_path + "/" if not self.abs_path.endswith("/") else self.abs_path


    def add_child(self, name: str, node_type: str, abs_path: str) -> 'FileTreeNode':
        if name not in self.children:
            self.children[name] = FileTreeNode(name=name, node_type=node_type, parent=self, abs_path=abs_path)
        return self.children[name]

    def is_dir(self) -> bool:
        return self.node_type == "d"

    def is_file(self) -> bool:
        return self.node_type == "f"

    def print_tree(self, level: int = 0):
        indent = "    " * level
        print(f"{indent}{self.name}/" if self.is_dir() else f"{indent}{self.name}")
        # 父节点优先打印目录，后打印文件，更清晰
        for child in sorted(self.children.values(), key=lambda x: (x.node_type, x.name)):
            child.print_tree(level + 1)
    
    def parse_json(self):
        # 映射为前端需要的格式

        '''
        return {
            "title": self.name,
            "node_type": self.node_type,
            "children": {name: child.parse_json() for name, child in self.children.items()},
            "id": self.abs_path,
            "field": self.abs_path
        }
        '''
        # 目录优先，文件后
        sorted_children = sorted(self.children.values(), key=lambda x: (x.node_type, x.name))
        return {
            "title": self.name,
            "node_type": self.node_type,
            "children": [child.parse_json() for child in sorted_children],
            "id": self.abs_path,
            "field": self.abs_path,
        }

    # -----  解析find输出并构建树 -----
    @staticmethod
    def build_file_tree_from_find_output(base_path: str, find_output: str) -> 'FileTreeNode':

        # cmd: cd <base_path> && find . -maxdepth 3 -printf "%p: %y\n"
        #     或者  cd <base_path> && find . -maxdepth 3

        root = FileTreeNode(name='.', abs_path=base_path, node_type="d")
        for line in find_output.strip().splitlines():
            if len(line) < 2:
                continue
            if line[-3] == ":":
                left = line[:-3]
                right = line[-1]
            else:
                left = line
                right = "u"
            # left, sep, right = line.rpartition(":")
            # if not sep:
            #     continue  # 跳过无效行（没有冒号分隔的内容）
            relpath = left.strip()
            node_type = right.strip()
            # 移除前导"./"（如果有），按"/"分割
            parts = relpath.lstrip("./").split("/") if relpath.lstrip("./") else []
            current = root
            for i, part in enumerate(parts):
                is_last = i == len(parts) - 1
                typ = node_type if is_last else "d"
                current = current.add_child(part, typ, 
                                            abs_path=current.abs_path + part + "/" if typ == "d" else current.abs_path + part)

                if not is_last:
                    current.node_type = "d"
                    current.abs_path = current.abs_path + "/" if not current.abs_path.endswith("/") else current.abs_path


        return root
